﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Microsoft.Azure.E2E.Common.Net
{
    /// <summary>
    /// A multipart message
    /// </summary>
    public class MultipartMessage : IDisposable
    {
        private readonly List<MessagePart> _parts = new List<MessagePart>();

        /// <summary>
        /// Creates a new multipart message
        /// </summary>
        /// <param name="boundary">The value to use as the boundary between parts of the message</param>
        public MultipartMessage(string boundary)
        {
            Boundary = boundary;
        }

        /// <summary>
        /// Adds a new part to the message
        /// </summary>
        /// <param name="part">The part to add</param>
        public void AddPart(MessagePart part)
        {
            _parts.Add(part);
        }

        /// <summary>
        /// Gets the boundary to use between parts of the message
        /// </summary>
        public string Boundary { get; private set; }

        /// <summary>
        /// Gets the multipart message as a stream
        /// </summary>
        /// <returns>A stream representing this multipart message</returns>
        public Stream GetStream()
        {
            var stream = new MultiStream();
            foreach (var part in _parts)
            {
                stream.AddStream(part.GetStream(this));
            }
            return stream;
        }

        /// <summary>
        /// Frees any resources used by the message
        /// </summary>
        /// <remarks>Calls <see cref="IDisposable.Dispose"/> on each of the contained parts</remarks>
        public void Dispose()
        {
            foreach (var part in _parts)
            {
                part.Dispose();
            }
        }
    }
}
